
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <errno.h>
#include <error.h>

#include "global_var.h"
#include "ans_code.h"
#include "socket.h"
#include "accept.h"

int fork_listen(char *v4_address, char *v6_address, short port)
{
	pid_t pid = -2;
	int v4_sfd = -2, v6_sfd = -2;

	if (v4_address != NULL)
	{
		v4_sfd = init_ipv4_socket(v4_address, port);
	}

	if (v6_address != NULL)
	{
		v6_sfd = init_ipv6_socket(v6_address, port);
	}

	if (v4_sfd != -2 && v6_sfd != -2)
		pid = fork();

	if (pid == 0) // in listen process
	{
		// redirect fd 0,1,2
		freopen("/dev/zero", "r", stdin);
		freopen(g_log_file_path, "a", stdout);
		freopen(g_log_file_path, "a", stderr);

		// entry point
		start_all_threads(v4_sfd, v6_sfd);
	}
	else // main process exit
	{
		if (v4_sfd == -2 && v6_sfd == -2)
			error(-2, EINVAL, "Forked no process for listen.\n");
		else if (v4_sfd != -2 && v4_sfd != -2)
			fprintf(stdout, "Forked process for ipv4/ipv6 listen, pid: %d.\n", pid);
		else if (v4_sfd != -2)
			fprintf(stdout, "Forked process for ipv4 listen, pid: %d.\n", pid);
		else if (v6_sfd != -2)
			fprintf(stdout, "Forked process for ipv6 listen, pid: %d.\n", pid);
	}
	return 0;
}

int main(int argc, char **argv)
{
	init_global_var(argc, argv);
	init_ans_string();
	fork_listen(g_ipv4_addr, g_ipv6_addr, g_port);
	return 0;
}
